from PyQt5.QtCore import QThread, pyqtSignal, QWaitCondition, QMutex

from videoprocessing import ShootCamera, save_img, save_img2
from shoot_util import create_dir,post_file,  generate_data, init_database, find_max_num,send_warn
from time import sleep
from client import send_data,receive_command
from socket import socket, AF_INET, SOCK_STREAM

shoot_flag=0
#0

def upload():
    create_dir()
    count=find_max_num()
    db = init_database()
    global shoot_flag
    while True:
        try:
            # data=generate_data()
            # print(data)
            # db.insert_history(data)
            # sleep(1)

            # shoot_flag=find_command()
            command = receive_command()
            if command.find('start') != -1:
                shoot_flag = 1
            elif command.find('pause') != -1:
                shoot_flag = 0
            elif command.find('stop') != -1:
                break

            print('当前指令：', command)

            if shoot_flag == 1:

                img_path, count = save_img(ShootCamera(0), count)
                send_flag = post_file(img_path, 'remote')  #
                data = generate_data()
                print(data)
                db.insert_history(data)


                if send_flag:
                    print(f'{img_path}上传成功')
                else:
                    print(f'{img_path}上传失败，请稍后再试')
            else:
                print('暂停拍摄')

        except Exception as e:
            print(e)
            db.close()

import sys
def upload2(command):
    create_dir()

    db = init_database()
    global shoot_flag
    try:
            # data=generate_data()
            # print(data)
            # db.insert_history(data)
            # sleep(1)

            # shoot_flag=find_command()
            #command = receive_command()
            if command.find('start') != -1:
                shoot_flag = 1
            elif command.find('pause') != -1:
                shoot_flag = 0

            # elif command.find('stop') != -1:
            #     break

            print('当前指令：', command)

            if shoot_flag == 1:

                img_path = save_img2(ShootCamera(0))

                data = generate_data(img_path)
                print(data)
                db.insert_history(data)
                temp = float(data[0][3])
                # if temp > 30 or temp < 20:
                #     try:
                #         sys.excepthook=send_warn(new=f'温度达到{temp}异常!', sec=5)
                #     except Exception as e:
                #         print(e)
                send_flag = post_file(img_path, 'remote')  #
                if send_flag:
                    print(f'{img_path}上传成功')
                else:
                    print(f'{img_path}上传失败，请稍后再试')

                return data#[0]

            else:
                print('暂停拍摄')
                return None

    except Exception as e:
            print(e)
            db.close()
            return None


# 新开一个线程进行循环的操作
class Upload(QThread):
    # 线程值信号
    valueChange = pyqtSignal(int)

    # 构造函数
    def __init__(self):
        super(Upload, self).__init__()
        self.isPause = False
        self.isCancel=False
        self.cond = QWaitCondition()
        self.mutex = QMutex()

     # 暂停
    def pause(self):
        print("线程暂停")
        self.isPause = True

    # 恢复
    def resume(self):
        print("线程恢复")
        self.isPause = False
        self.cond.wakeAll()

    # 取消
    def cancel(self):
        print("线程取消")
        self.isCancel = True
        # 大循环
    def run(self):
        create_dir()
        count = find_max_num()
        db = init_database()
        global shoot_flag
        while True:
            # 线程锁on
            self.mutex.lock()
            if self.isPause:
                self.cond.wait(self.mutex)
            if self.isCancel:
                self.valueChange.emit(0)
                break

            try:
                # data=generate_data()
                # print(data)
                # db.insert_history(data)
                # sleep(1)

                # shoot_flag=find_command()
                command = receive_command()
                if command.find('start') != -1:
                    shoot_flag = 1
                elif command.find('pause') != -1:
                    shoot_flag = 0
                elif command.find('stop') != -1:
                    break

                print('当前指令：', command)

                if shoot_flag == 1:

                    img_path, count = save_img(ShootCamera(0), count)
                    send_flag = post_file(img_path, 'remote')  #
                    data = generate_data()
                    print(data)
                    db.insert_history(data)

                    if send_flag:
                        print(f'{img_path}上传成功')
                    else:
                        print(f'{img_path}上传失败，请稍后再试')
                else:
                    print('暂停拍摄')

            except Exception as e:
                print(e)
                db.close()

            # 线程锁off
            self.mutex.unlock()

class Receive(QThread):
    # 线程值信号
    valueChange = pyqtSignal(int)

    # 构造函数
    def __init__(self):
        super(Receive, self).__init__()
        self.control_command=None
        self.t_command=None

    def run(self):
        while True:
            try:

                command = receive_command(None)

                print('当前指令：', command)
                if (command=='start') or (command=='pause'):
                    self.control_command=command#return command
                elif (command=='5s') or (command=='10s') or (command=='30s') or (command.find('min')!=-1):
                    self.t_command=command
                    print('收到时间指令')

            except Exception as e:
                print(e)

    def get_command(self):
        return self.control_command,self.t_command

from playsound import playsound
from PyQt5.QtCore import Qt, QElapsedTimer,QObject
from PyQt5.QtWidgets import QApplication, QLabel, QDialog
from sys import exit,argv

class Worker(QThread):
    finished = pyqtSignal()

    def __init__(self, new, sec):
        super().__init__()
        self.new = new
        self.sec = sec

    def run(self):
        app = QApplication([])
        dialog = QDialog()
        dialog.setWindowTitle('警告')
        dialog.setWindowFlags(Qt.WindowTitleHint | Qt.WindowCloseButtonHint)
        label = QLabel(dialog)
        label.setAlignment(Qt.AlignCenter)
        label.setText(self.new + f'({self.sec}s)')
        label.setStyleSheet('font-size: 20px;')
        label.adjustSize()
        dialog.adjustSize()
        dialog.show()

        timer = QElapsedTimer()
        timer.start()
        while timer.elapsed() < self.sec * 1000:
            remaining_time = (self.sec * 1000 - timer.elapsed()) // 1000
            label.setText(self.new + f'({remaining_time}s)')  # str(remaining_time)
            QApplication.processEvents()
            playsound('sound/warn.wav')
            if not label.parent():
                return
        dialog.close()
        self.finished.emit()

def send_warn2(new='温度异常!', sec=5):
    worker = Worker(new, sec)
    worker.start()
    worker.finished.connect(worker.deleteLater)

if __name__ =='__main__':
    send_warn2(new='温度异常!', sec=5)

    # create_dir()
    # count = find_max_num()
    # db=init_database()
    #
    # while True:
    #     try:
    #         # data=generate_data()
    #         # print(data)
    #         # db.insert_history(data)
    #         # sleep(1)
    #
    #         #shoot_flag=find_command()
    #         command = receive_command()
    #         if command.find('start') != -1:
    #             shoot_flag = 1
    #         elif command.find('pause') != -1:
    #             shoot_flag = 0
    #         elif command.find('stop') != -1:
    #             break
    #
    #         print('当前指令：', command)
    #
    #         if shoot_flag==1:
    #             #data = str(count)
    #             #send_data(data)#info =
    #             # print('接收服务端的信息：', info)
    #             # if info.find('pause')!=-1:
    #             #     shoot_flag=0
    #             # elif info.find('stop')!=-1:
    #             #     break
    #             # elif info.find('start')!=-1:
    #             #     shoot_flag=1
    #             img_path, count=save_img(ShootCamera(0),count)
    #             send_flag=post_file(img_path,'remote')#
    #             data = generate_data()
    #             print(data)
    #             db.insert_history(data)
    #             # if count<=3:
    #             #     sleep(3)
    #             # # elif count>3 and count<7:
    #             # #     sleep(5)
    #             # else:
    #             #     sleep(5)
    #
    #             if send_flag:
    #                 print(f'{img_path}上传成功')
    #             else:
    #                 print(f'{img_path}上传失败，请稍后再试')
    #         else:
    #             print('暂停拍摄')
    #
    #     except Exception as e:
    #         print(e)
    #         db.close()